<template>
    <div>
        <pagetitle type="2"></pagetitle>
        <el-card>
            <div class="setioncard">
                <div class="headers">
                    <!-- <el-image class="userHeaderImg" v-if="storeUserInfo.pic" :src="storeUserInfo.pic" imgType="2" :preview-src-list="[storeUserInfo.pic]" fit="cover"> </el-image> -->
                    <!-- <el-image class="userHeaderImg" v-else :src="require('@/assets/image/userinfoimg.png')" fit="cover"></el-image> -->
                    <images v-if="storeUserInfo.pic" :src="storeUserInfo.pic" class="userHeaderImg" imgType="1" />
                    <el-image class="userHeaderImg" v-else :src="require('@/assets/image/userinfoimg.png')" fit="cover"></el-image>
                    <div class="names text-overflow1" :title="storeUserInfo.nickName">{{ storeUserInfo.nickName }}</div>
                </div>
                <div class="functionBox">
                    <div class="functionName">账号与安全</div>
                    <div class="paragraph">
                        <div class="paragraphName">
                            <div class="names">登录方式</div>
                            <div class="namesTip">您可用户账号信息、手机号登录云上农场账号</div>
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">账号信息</div>
                                    <div class="paragraphItemMsgCont">{{ storeUserInfo.nickName }}</div>
                                </div>
                                <sxnfbtn @click="updateUserName(storeUserInfo.nickName)">更改</sxnfbtn>
                                <!-- <div class="paragraphItemBtn" @click="updateUserName(storeUserInfo.nickName)">更改</div> -->
                            </div>
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq1.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">手机号</div>
                                    <div class="paragraphItemMsgCont">{{ cutOutPhone(storeUserInfo.phoneNum) }}</div>
                                </div>
                                <sxnfbtn @click="setUserPhones(1)">更改</sxnfbtn>
                                <!-- <div class="paragraphItemBtn" @click="setUserPhones(1)">更改</div> -->
                            </div>
                        </div>
                    </div>
                    <!-- 暂时取消 -->
                    <!-- <div class="paragraph">
                        <div class="paragraphName">
                            <div class="names">安全验证</div>
                            <div class="namesTip">有助于保护您的账号安全</div>
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq4.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">双重验证（未开启）</div>
                                    <div class="paragraphItemMsgCont">开启后，每次登录账号，均需进一步验证</div>
                                </div>
                                <div class="paragraphItemBtn" @click="openAccountDialog(1)">开启</div>
                            </div>
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq5.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">安全手机号</div>
                                    <div class="paragraphItemMsgCont"><span>未设置</span></div>
                                </div>
                                <div class="paragraphItemBtn" @click="setUserPhones(2)">设置</div>
                            </div>
                        </div>
                    </div> -->
                    <div class="paragraph">
                        <div class="paragraphName">
                            <div class="names">安全中心</div>
                            <!-- <div class="namesTip">有助于保护您的账号安全</div> -->
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq6.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">重置密码</div>
                                    <div class="paragraphItemMsgCont">上一次重置密码：2023年11月10日18:00</div>
                                </div>
                                <sxnfbtn @click="updatePasswords = true">重置</sxnfbtn>
                                <!-- <div class="paragraphItemBtn" @click="updatePasswords = true">重置</div> -->
                            </div>
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq7.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">冻结账号</div>
                                    <div class="paragraphItemMsgCont">若怀疑账号被盗，可紧急冻结账号</div>
                                </div>
                                <el-image class="paragraphItemRight" :src="require('@/assets/image/up.png')" fit="cover" @click="openAccountDialog(2)"></el-image>
                            </div>
                        </div>
                        <div class="paragraphItem">
                            <el-image class="paragraphItemImg" :src="require('@/assets/image/aq9.png')" fit="cover"></el-image>
                            <div class="paragraphItemcont">
                                <div class="paragraphItemMsg">
                                    <div class="paragraphItemMsgName">注销账号</div>
                                    <div class="paragraphItemMsgCont">永久删除您的账号及相关数据，管理您的注销请求</div>
                                </div>
                                <el-image class="paragraphItemRight" :src="require('@/assets/image/up.png')" fit="cover" @click="openAccountDialog(3)"></el-image>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>
        <!-- 修改用户手机号码----设置安全手机号 -->
        <el-dialog v-model="dialogVisible" :title="form.dialogName" width="500">
            <el-form :model="form" label-width="auto" style="max-width: 600px">
                <el-form-item label="手机号码" v-if="form.step == 1">
                    {{ cutOutPhone(storeUserInfo.phoneNum) }}
                </el-form-item>
                <el-form-item :label="form.dialogType == 1 ? '新手机号码' : '安全手机号'" v-else>
                    <el-input v-model="form.newPhone" :placeholder="form.dialogType == 1 ? '新的手机号码' : '安全手机号'" />
                </el-form-item>
                <el-form-item label="验证码">
                    <el-input v-model="form.code" placeholder="验证码">
                        <template #append>
                            <el-button @click="setCodeTimer(form.step == 1 ? storeUserInfo.phoneNum : form.newPhone, 1)">{{ phoneCodeText }}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <div v-if="form.step == 1">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="setStep(2)"> 下一步 </el-button>
                    </div>
                    <div v-else>
                        <el-button @click="setStep(1)">上一步</el-button>
                        <el-button type="primary" @click="setUserPhone"> 确定 </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
        <!-- 开启双重验证 -- 冻结账号 -- 解冻账号 -- 注销账户 -->
        <el-dialog v-model="dualVaerification" :title="accountData.dialogName" width="500">
            <el-form :model="accountData" label-width="auto" style="max-width: 600px">
                <el-form-item label="手机号码">
                    {{ cutOutPhone(storeUserInfo.phoneNum) }}
                </el-form-item>
                <el-form-item label="验证码">
                    <el-input v-model="accountData.code" placeholder="验证码">
                        <template #append>
                            <el-button @click="setCodeTimer(storeUserInfo.phoneNum, 2)">{{ phoneCodeText }}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dualVaerification = false">取消</el-button>
                    <el-button type="primary" @click="accountHandle"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 修改密码 -->
        <el-dialog v-model="updatePasswords" title="修改密码" width="500">
            <el-form :model="newPwds" label-width="auto" style="max-width: 600px">
                <div v-if="newPwds.step == 1">
                    <el-form-item label="手机号码">
                        {{ cutOutPhone(storeUserInfo.phoneNum) }}
                    </el-form-item>
                    <el-form-item label="验证码">
                        <el-input v-model="newPwds.code" placeholder="验证码">
                            <template #append>
                                <el-button @click="setCodeTimer(storeUserInfo.phoneNum, 1)">{{ phoneCodeText }}</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </div>
                <div v-else>
                    <el-form-item label="旧密码">
                        <el-input v-model="newPwds.oldpassword" show-password placeholder="请输入旧密码"> </el-input>
                    </el-form-item>
                    <el-form-item label="新密码">
                        <el-input v-model="newPwds.newPassword" show-password placeholder="请输入新密码"> </el-input>
                    </el-form-item>
                    <el-form-item label="确认新密码">
                        <el-input v-model="newPwds.doublePassword" show-password placeholder="确认新密码"> </el-input>
                    </el-form-item>
                    <el-form-item label="">
                        <span style="font-size: 12px; color: #666666">温馨提示：密码长度不能小于8个字符,至少含字母和数字，不能包含空格</span>
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <div v-if="newPwds.step == 1">
                        <el-button @click="updatePasswords = false">取消</el-button>
                        <el-button type="primary" @click="setPwdStep(2)"> 下一步 </el-button>
                    </div>
                    <div v-else>
                        <el-button @click="setPwdStep(1)">上一步</el-button>
                        <el-button type="primary" @click="setUserPassword"> 确定 </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, watch } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage, ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
import { getUpdateMsgCode, setUserNickName, getUserInfo, verificationCodePhone, updateUsersPhone, updateUsersPassword, sendCancelValidateCode, unsubscribe } from "@/api/user";

import { Md5 } from "ts-md5";
const store = useStore();

const router = useRouter();
// 发送短信定时器相关

const phoneCodeText = ref("获取验证码");
let codeTimer: any = "";

const time = ref(60);
const setCodeTimer = (phone: number | string, type: number | string) => {
    if (time.value < 60) {
        return;
    } else {
        codeTimer = setInterval(() => {
            if (time.value > 0) {
                phoneCodeText.value = `${time.value} S 后重新获取`;
                time.value -= 1;
            } else {
                clearInterval(codeTimer);
                phoneCodeText.value = "获取验证码";
                time.value = 60;
            }
        }, 1000);
        if (type == 1) {
            // 修改密码验证码
            getUpdateMsgCode({ phone })
                .then((res: any) => {
                    ElMessage.success("短信发送成功");
                })
                .catch((err) => {
                    clearInterval(codeTimer);
                    ElMessage.error(err);
                    phoneCodeText.value = "获取验证码";
                });
        } else if (type == 2) {
            // 注销账号验证码
            sendCancelValidateCode({ phone })
                .then((res: any) => {
                    ElMessage.success("短信发送成功");
                })
                .catch((err) => {
                    clearInterval(codeTimer);
                    ElMessage.error(err);
                    phoneCodeText.value = "获取验证码";
                });
        }
    }
};
// 取消定时器
const clearTimer = () => {
    clearInterval(codeTimer);
    time.value = 60;
    phoneCodeText.value = "获取验证码";
};

// 获取个人信息
const storeUserInfo: any = computed((e: any) => {
    return store.getters.userInfo;
});
// 修改个人昵称
const updateUserName = (name: string) => {
    ElMessageBox.prompt("请输入您的昵称", "修改昵称", {
        confirmButtonText: "确定",
        inputValue: name,
        inputPlaceholder: "请输入您的昵称",
        inputPattern: /^\S*\S$/,
        inputErrorMessage: "昵称不能为空且不能以空格开头和结尾",
        callback: (action: any) => {
            setUserNickName(action.value).then((res: any) => {
                ElMessage.success("修改成功");
                getUserInfo().then((res: any) => {
                    store.commit("setUserInfo", res.data);
                });
            });
        },
    });
};
// 修改用户手机号码---设置安全手机号
const dialogVisible = ref(false);
const form: any = reactive({
    newPhone: "",
    code: "",
    step: 1,
    dialogType: 1,
    dialogName: "修改手机号码",
});
const setStep = (num: number) => {
    if (!form.code && num == 2) {
        ElMessage.error("验证码不能为空");
        return;
    }
    // 进行第二步操作
    if (num == 2) {
        verificationCodePhone(form.code).then((res: any) => {
            form.code = "";
            form.step = num;
            clearTimer();
        });
    } else {
        clearTimer();
        form.step = num;
    }
};
// 打开设置手机号码对话框
const setUserPhones = (type: number) => {
    form.dialogType = type;
    if (type == 1) {
        form.dialogName = "修改手机号码";
    } else {
        form.dialogName = "设置安全手机号";
    }
    dialogVisible.value = true;
};
// 设置手机号确定按钮
const setUserPhone = () => {
    if (!form.code && form.step == 2) {
        ElMessage.error("验证码不能为空");
        return;
    }
    if (form.dialogType == 1) {
        // 修改手机号码
        updateUsersPhone({
            phone: form.newPhone,
            validateCode: form.code,
        }).then((res: any) => {
            ElMessage.success("修改成功");
            getUserInfo().then((res: any) => {
                store.commit("setUserInfo", res.data);
            });
        });
    } else {
        // 设置安全手机号
    }
    clearTimer();
    form.step = 1;
    form.code = "";
    form.newPhone = "";
    dialogVisible.value = false;
};
// 开启双重验证
const dualVaerification = ref(false);
const accountData = reactive({
    code: "",
    dialogName: "开启双重验证",
});
const openAccountDialog = (num: number) => {
    if (num == 1) {
        accountData.dialogName = "开启双重验证";
        dualVaerification.value = true;
    } else if (num == 2) {
        accountData.dialogName = "冻结账号";
        dualVaerification.value = true;
    } else {
        ElMessageBox.confirm("注销后将永久删除您的账号及相关数据，确定要进行此操作吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }).then(() => {
            accountData.dialogName = "注销账号";
            dualVaerification.value = true;
        });
    }
};
const accountHandle = () => {
    if (accountData.code == "") {
        ElMessage.error("验证码不能为空");
        return;
    }
    if (accountData.dialogName == "注销账号") {
        console.log(storeUserInfo.value.phoneNum);
        // return;
        unsubscribe({
            validateCode: accountData.code,
            phone: storeUserInfo.value.phoneNum,
        }).then((res) => {
            router.replace("/login");
            store.commit("setToken", "");
            sessionStorage.clear();
        });
    }
};
// 修改密码
const updatePasswords = ref(false);
const newPwds = reactive({
    oldpassword: "",
    newPassword: "",
    doublePassword: "",
    code: "",
    step: 1,
});
const setPwdStep = (num: number) => {
    if (!newPwds.code && num == 2) {
        ElMessage.error("验证码不能为空");
        return;
    }
    // 进行第二步操作
    if (num == 2) {
        verificationCodePhone(newPwds.code).then((res: any) => {
            // newPwds.code = "";
            newPwds.step = num;
            clearTimer();
        });
    } else {
        clearTimer();
        newPwds.step = num;
    }
};
const setUserPassword = () => {
    if (!newPwds.code && newPwds.step == 2) {
        ElMessage.error("验证码不能为空");
        return;
    }
    if (!newPwds.oldpassword) {
        ElMessage.error("请输入原密码");
        return;
    }
    if (!newPwds.newPassword) {
        ElMessage.error("请输入新密码");
        return;
    }
    if (newPwds.newPassword != newPwds.doublePassword) {
        ElMessage.error("两次密码输入不一致");
        return;
    }
    const regs = /^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{8,}$/;
    if (!regs.test(newPwds.newPassword)) {
        ElMessage.error("密码长度不能小于8个字符,至少含字母和数字，不能包含空格");
        return;
    }
    const md5: any = new Md5();
    const md51: any = new Md5();
    const postDatas = {
        validateCode: newPwds.code,
        oldPassword: md5.appendAsciiStr(newPwds.oldpassword).end(),
        newPassword: md51.appendAsciiStr(newPwds.newPassword).end(),
    };
    updateUsersPassword(postDatas).then((res: any) => {
        ElMessage.success("密码重置成功");
        newPwds.step = 1;
        newPwds.code = "";
        newPwds.oldpassword = "";
        newPwds.newPassword = "";
        newPwds.doublePassword = "";
        updatePasswords.value = false;
    });
};
/**
 * 手机号码截取
 * @param phone 手机号码
 */
const cutOutPhone = (phone: string) => {
    if (!phone) {
        return;
    }
    const pn = phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    return pn;
};
watch(updatePasswords, (val: any) => {
    if (!val) {
        newPwds.code = "";
        newPwds.newPassword = "";
        newPwds.oldpassword = "";
        newPwds.doublePassword = "";
        newPwds.step = 1;
        clearTimer();
    }
});
watch(dialogVisible, (val: any) => {
    if (!val) {
        form.code = "";
        form.newPhone = "";
        form.dialogType = 1;
        form.dialogName = "修改手机号码";
        form.step = 1;
    }
});
watch(dualVaerification, (val: any) => {
    if (!val) {
        clearTimer();
    }
});
</script>
<style lang="scss" scoped>
.setioncard {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;
    .headers {
        width: 100px;
        padding-top: 30px;
        padding-left: 50px;
        margin-right: 100px;
        .userHeaderImg {
            width: 80px;
            height: 80px;
            border-radius: 100%;
            overflow: hidden;
        }
        .names {
            margin-top: 15px;
            color: #333333;
            font-size: 16px;
            width: 80px;
            text-align: center;
        }
    }
    .functionBox {
        width: 100%;
        .functionName {
            color: #333333;
            font-size: 28px;
            padding-top: 28px;
            padding-bottom: 20px;
        }
        .paragraph {
            margin-top: 40px;
            .paragraphName {
                margin-bottom: 20px;
                .names {
                    color: #333333;
                    font-size: 18px;
                }
                .namesTip {
                    color: #999999;
                    font-size: 14px;
                    margin-top: 5px;
                }
            }
            .paragraphItem {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                .paragraphItemImg {
                    width: 36px;
                    height: 36px;
                    border-radius: 100%;
                    margin-right: 20px;
                }
                .paragraphItemcont {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 720px;
                    border-bottom: 1px solid #eeeeee;
                    padding-bottom: 20px;
                    padding-top: 20px;
                    .paragraphItemMsgName {
                        color: #333333;
                        font-size: 16px;
                    }
                    .paragraphItemMsgCont {
                        color: #666666;
                        font-size: 14px;
                        margin-top: 2px;
                        span {
                            color: #f80000;
                        }
                    }
                    .paragraphItemBtn {
                        width: 80px;
                        height: 36px;
                        background: #eeeeee;
                        color: #299c37;
                        font-size: 14px;
                        border-radius: 5px;
                        text-align: center;
                        line-height: 36px;
                        cursor: pointer;
                    }
                    .paragraphItemRight {
                        width: 18px;
                        height: 10px;
                        transform: rotate(90deg);
                        cursor: pointer;
                    }
                }
            }
        }
    }
}
</style>
